<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-header">
        <div class="logo">
          <i class="el-icon-s-platform"></i>
        </div>
        <h1 class="register-title">企业用户注册</h1>
        <p class="register-subtitle">三步完成注册 · 开启智能用工</p>
      </div>

      <el-steps :active="active" finish-status="success" simple class="custom-steps">
        <el-step title="企业基本信息"></el-step>
        <el-step title="法人信息"></el-step>
        <el-step title="账户信息"></el-step>
      </el-steps>

      <el-form :model="registerForm" :rules="rules" ref="registerFormRef" label-width="100px" class="register-form">
        <!-- 第一步：企业基本信息 -->
        <div v-if="active === 0" >
          <el-form-item label="公司名称" prop="companyName">
            <el-input v-model="registerForm.companyName" placeholder="请输入公司名称" class="custom-input"></el-input>
          </el-form-item>
          <el-form-item label="公司地址" prop="companyAddress">
            <el-input v-model="registerForm.companyAddress" placeholder="请输入公司地址" class="custom-input"></el-input>
          </el-form-item>
          <el-form-item label="公司类型" prop="companyType">
            <el-select v-model="registerForm.companyType" placeholder="请选择公司类型" class="custom-select" style="width: 100%">
              <el-option label="有限责任公司" value="有限责任公司"></el-option>
              <el-option label="股份有限公司" value="股份有限公司"></el-option>
              <el-option label="个人独资企业" value="个人独资企业"></el-option>
              <el-option label="合伙企业" value="合伙企业"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
        </div>

        <!-- 第二步：法人信息 -->
        <div v-if="active === 1">
          <el-form-item label="法人姓名" prop="legalName">
            <el-input v-model="registerForm.legalName" placeholder="请输入法人姓名" class="custom-input"></el-input>
          </el-form-item>
          <el-form-item label="联系方式" prop="legalPhone">
            <el-input v-model="registerForm.legalPhone" placeholder="请输入法人手机号" class="custom-input"></el-input>
          </el-form-item>
          <el-form-item label="身份证号" prop="legalIdCard">
            <el-input v-model="registerForm.legalIdCard" placeholder="请输入法人身份证号" class="custom-input"></el-input>
          </el-form-item>
        </div>

        <!-- 第三步：账户信息 -->
        <div v-if="active === 2">
          <el-form-item label="银行账户" prop="bankAccount">
            <el-input v-model="registerForm.bankAccount" placeholder="请输入企业银行账户" class="custom-input"></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="registerForm.username" placeholder="请设置用户名（6-20位字母或数字）" class="custom-input"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="registerForm.password" type="password" placeholder="请设置密码（8-20位，包含字母和数字）" class="custom-input"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码" class="custom-input"></el-input>
          </el-form-item>
          <el-form-item prop="agreement">
            <el-checkbox v-model="registerForm.agreement" class="agreement-checkbox">
              我已阅读并同意<a href="javascript:;" class="agreement-link">《用户协议》</a>和<a href="javascript:;" class="agreement-link">《隐私政策》</a>
            </el-checkbox>
          </el-form-item>
        </div>

        <el-form-item class="action-buttons">
          <div class="button-group">
            <el-button v-if="active > 0" @click="prev" class="step-btn prev-btn">
              <i class="el-icon-arrow-left"></i> 上一步
            </el-button>
            <div class="next-action">
              <template v-if="active < 2">
                <el-button type="primary" @click="next" class="step-btn next-btn">
                  下一步 <i class="el-icon-arrow-right"></i>
                </el-button>
                <router-link to="/login" class="back-link">返回登录</router-link>
              </template>
              <template v-else>
                <el-button type="primary" @click="submitForm" class="step-btn next-btn">
                  提交注册 <i class="el-icon-check"></i>
                </el-button>
                <el-button type="primary" @click="$router.push('/login')" class="step-btn next-btn">
                  返回登录 <i class="el-icon-back"></i>
                </el-button>
              </template>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <div class="login-link">
        已有账号？<router-link to="/login" class="link">立即登录</router-link>
      </div>
    </div>

    <div class="copyright">
      ©2023 智慧零工平台 版权所有
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { registerCompany, validateStep } from '../api/auth'

const router = useRouter()
const registerFormRef = ref(null)
const active = ref(0)

const registerForm = reactive({
  companyName: '',
  companyAddress: '',
  companyType: '',
  legalName: '',
  legalPhone: '',
  legalIdCard: '',
  bankAccount: '',
  username: '',
  password: '',
  confirmPassword: '',
  agreement: false
})

const validatePass2 = (rule, value, callback) => {
  if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
    { min: 2, max: 50, message: '公司名称长度在2到50个字符之间', trigger: 'blur' }
  ],
  companyAddress: [{ required: true, message: '请输入公司地址', trigger: 'blur' }],
  companyType: [{ required: true, message: '请选择公司类型', trigger: 'change' }],
  legalName: [
    { required: true, message: '请输入法人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '法人姓名长度在2到20个字符之间', trigger: 'blur' }
  ],
  legalPhone: [
    { required: true, message: '请输入法人手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  legalIdCard: [
    { required: true, message: '请输入法人身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
  ],
  bankAccount: [
    { required: true, message: '请输入银行账户', trigger: 'blur' },
    { pattern: /^\d{16,19}$/, message: '请输入正确的银行账号', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '用户名长度在4到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/, message: '密码必须包含字母和数字，长度在8-20位之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ],
  agreement: [{ required: true, message: '请阅读并同意用户协议和隐私政策', trigger: 'change' }]
}

const next = () => {
  if (active.value === 0) {
    const step1Data = {
      companyName: registerForm.companyName,
      companyAddress: registerForm.companyAddress,
      companyType: registerForm.companyType,
      step: 0
    }
    validateStep(step1Data).then(res => {
      if (res.code === 200) {
        active.value++
      } else {
        ElMessage.error(res.message)
      }
    }).catch(err => {
      ElMessage.error(err.message || '验证失败')
    })
  } else if (active.value === 1) {
    const step2Data = {
      legalName: registerForm.legalName,
      legalPhone: registerForm.legalPhone,
      legalIdCard: registerForm.legalIdCard,
      step: 1
    }
    validateStep(step2Data).then(res => {
      if (res.code === 200) {
        active.value++
      } else {
        ElMessage.error(res.message)
      }
    }).catch(err => {
      ElMessage.error(err.message || '验证失败')
    })
  } else if (active.value === 2) {
    // 验证第三步的表单
    registerFormRef.value.validateField(['bankAccount', 'username', 'password', 'confirmPassword', 'agreement'], (valid) => {
      if (!valid) {
        submitForm()
      }
    })
  }
}

const prev = () => {
  active.value--
}

const submitForm = () => {
  registerFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        console.log('开始提交企业注册表单:', {
          companyName: registerForm.companyName,
          companyAddress: registerForm.companyAddress,
          companyType: registerForm.companyType,
          legalName: registerForm.legalName,
          legalPhone: registerForm.legalPhone,
          username: registerForm.username,
          // 不打印密码等敏感信息
        });
        
        const response = await registerCompany(registerForm);
        console.log('注册响应:', response);
        
        if (response.code === 200) {
          ElMessage.success('注册成功，请登录');
          router.push('/login');
        } else {
          ElMessage.error(response.message || '注册失败，请稍后再试');
        }
      } catch (error) {
        console.error('注册过程发生错误:', error);
        ElMessage.error(error.message || '注册失败，请稍后再试');
      }
    } else {
      console.log('表单验证未通过');
      return false;
    }
  });
}
</script>

<style scoped>

.custom-steps {
  background: transparent;
}

.custom-steps :deep(.el-step.is-simple .el-step__title) {
  color: #5c5959!important;
}

.custom-steps :deep(.el-step.is-simple .el-step__icon-inner) {
  color: #5c5959!important;
}

.custom-steps :deep(.el-step.is-simple .el-step__arrow) {
  background: transparent !important;
}


.custom-steps :deep(.el-step.is-simple.is-process .el-step__title) {
  background: linear-gradient(90deg, #6dd5fa, #2980b9);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: url('image/Register.jpg') no-repeat center center / cover;
  background-color: rgba(0, 0, 0, 0.7);
  padding: 20px;
  position: relative;
}

.register-box {
  width: 500px;
  padding: 40px 30px;
  background: rgba(255, 255, 255, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 20px;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.6);
  text-align: center;
  animation: floatIn 1s ease-out forwards;
}

@keyframes floatIn {
  0% { opacity: 0; transform: translateY(40px) scale(0.95); }
  100% { opacity: 1; transform: translateY(0) scale(1); }
}

.register-header {
  margin-bottom: 30px;
}

.logo i {
  font-size: 48px;
  color: #5dade2;
  margin-bottom: 10px;
  animation: pulse 2s infinite alternate;
}

@keyframes pulse {
  0% { transform: scale(1); opacity: 1; }
  100% { transform: scale(1.1); opacity: 0.8; }
}

.register-title {
  font-size: 28px;
  font-weight: bold;
  background: linear-gradient(90deg, #6dd5fa, #2980b9);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.register-subtitle {
  font-size: 14px;
  color: #5c5959;
  margin-top: 8px;
}

.custom-steps {
  margin: 0 auto 30px;
  max-width: 90%;
}

.custom-steps :deep(.el-step__title) {
  color: #c0c4cc;
  font-size: 14px;
}

.custom-steps :deep(.el-step.is-simple .el-step__arrow::before) {
  background: linear-gradient(90deg, #6dd5fa, #2980b9);
}

.custom-steps :deep(.el-step.is-simple .el-step__arrow::after) {
  background: linear-gradient(90deg, #6dd5fa, #2980b9);
}

.register-form {
  margin-top: 20px;
}

.custom-input, .custom-select {
  margin-bottom: 20px;
}

.custom-input input, .custom-select :deep(.el-input__inner) {
  background: transparent !important;
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #fff;
  padding: 12px 15px 12px 35px;
  font-size: 16px;
  border-radius: 8px;
  height: 48px;
}

.custom-input input::placeholder, .custom-select :deep(.el-input__inner::placeholder) {
  color: #bbb;
}

.custom-input:hover input,
.custom-input:focus-within input,
.custom-select:hover :deep(.el-input__inner),
.custom-select:focus-within :deep(.el-input__inner) {
  border-color: #409EFF;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.6);
}

.custom-input :deep(.el-input__prefix), .custom-select :deep(.el-input__prefix) {
  color: #5dade2;
  left: 10px;
}

.action-buttons {
  margin-top: 30px;
}

.button-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.next-action {
  display: flex;
  align-items: center;
  gap: 20px;
}

.back-link {
  color: #5dade2;
  text-decoration: none;
  font-size: 14px;
  white-space: nowrap;
}

.back-link:hover {
  text-decoration: underline;
}

.step-btn {
  width: 100px;
  height: 40px;
  font-size: 14px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.prev-btn {
  background: linear-gradient(90deg, #409EFF, #66b1ff);
  border: none;
  color: white;
}

.prev-btn:hover {
  background: linear-gradient(90deg, #66b1ff, #409EFF);
  box-shadow: 0 0 16px rgba(64, 158, 255, 0.7);
}

.next-btn, .register-btn {
  background: linear-gradient(90deg, #409EFF, #66b1ff);
  border: none;
  color: white;
}

.next-btn:hover, .register-btn:hover {
  background: linear-gradient(90deg, #66b1ff, #409EFF);
  box-shadow: 0 0 16px rgba(64, 158, 255, 0.7);
}

.agreement-checkbox {
  color: #c0c4cc;
}

.agreement-link {
  color: #5dade2;
  text-decoration: none;
  margin: 0 5px;
}

.agreement-link:hover {
  text-decoration: underline;
}

.login-link {
  text-align: center;
  margin-top: 25px;
  font-size: 14px;
  color: #c0c4cc;
}

.link {
  color: #5dade2;
  text-decoration: none;
  margin-left: 5px;
}

.link:hover {
  text-decoration: underline;
}

.copyright {
  position: absolute;
  bottom: 20px;
  text-align: center;
  width: 100%;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.4);
}

/* 修改表单项字体颜色 */
.el-form-item__label {
  color: #c0c4cc; /* 修改为与副标题相同的颜色 */
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-box {
    width: 90%;
    padding: 30px 20px;
  }

  .action-buttons {
    flex-direction: column;
    align-items: center;
  }

  .step-btn {
    width: 100%;
    margin-bottom: 10px;
  }
}
</style>